package com.tencent.cloud.iov.block;

import android.view.View;
import android.view.ViewGroup;

import com.tencent.cloud.iov.action.IActionListener;

/**
 * 区块布局抽象类
 *
 * 保存数据、视图、位置信息，并提供行为绑定的空实现，子类可选择性实现行为绑定
 *
 * @author showxiao
 * @date 2018/3/28
 */

public abstract class BaseBlockLayout<T> implements IBlockLayout<T>, View.OnAttachStateChangeListener {

    private static final String TAG = "BaseBlockLayout";

    private T mItem;
    private View mView;
    private int mPosition;
    private IActionListener mActionListener;

    public BaseBlockLayout() {
    }

    @Override
    public final View onCreateView(ViewGroup parent) {
        mView = createView(parent);
        mView.addOnAttachStateChangeListener(this);
        return mView;
    }

    @Override
    public final void onBindView(T item, int position) {
        mItem = item;
        mPosition = position;
        bindView(item, position);
    }

    @Override
    public final void onBindAction(T item, int position, IActionListener actionListener) {
        mActionListener = actionListener;
        bindAction(item, position, actionListener);
    }

    /**
     * 视图（重新）挂载至窗口
     *
     * 可以在此回调里恢复暂停的视图动画
     *
     * @param v
     */
    @Override
    public void onViewAttachedToWindow(View v) {

    }

    /**
     * 视图从窗口上移除
     *
     * 可以在此回调里暂停视图动画，避免后台动画导致 CPU 消耗
     *
     * @param v
     */
    @Override
    public void onViewDetachedFromWindow(View v) {

    }

    /**
     * 创建布局视图
     *
     * @param parent    父视图
     * @return          创建的视图
     */
    protected abstract View createView(ViewGroup parent);

    /**
     * 绑定区块布局数据
     *
     * @param item          区块数据
     * @param position      区块位置下标
     */
    protected abstract void bindView(T item, int position);

    /**
     * 绑定区块布局行为
     * @param item              区块数据
     * @param position          区块位置下标
     * @param actionListener    区块行为响应视图
     */
    protected void bindAction(T item, int position, IActionListener actionListener) {

    }

    public final View getView() {
        return mView;
    }

    public final T getItem() {
        return mItem;
    }

    public final int getPosition() {
        return mPosition;
    }

    public final IActionListener getActionListener() {
        return mActionListener;
    }

    public final boolean onAction(String actionId, Object... args) {
        if (mActionListener != null) {
            return mActionListener.onAction(actionId, args);
        }
        return false;
    }
}
